// index.js
// 获取应用实例
const app = getApp()

import {
    register,
    distinguishIdCard, // 实名认证 点击身份证识别身份证信息
    getEcho, // 用户信息回显
    encryptedPhoneData,
    checkUserAccount,
    queryLogoutStatus
} from '../../api/app.js'
import {
    openSalaryCard,
    openSalaryVerify,
    querySalaryCard
} from '../../utils/salary-card.js'
import {
    queryVerifyResult
} from '../../api/salary-card'
import user from '../../utils/user'
import {
    inputchange,
    wxfileTobase64,
} from '../../utils/util.js'
import global from '../../utils/global'
// Idcard
Page({
    data: {
        authStatus: false,
        dataInformation: {
            id: '',
            userId: '',
            ownIdCardFront: '', // 身份证正面
            ownIdCardBack: '', // 身份证反面
            openId: '',
            userName: '', // 身份证姓名
            userHeadUrl: '',
            idCardNo: '', // 身份证号
            phone: '',
        },
        judgeId: true,
        isEdit: false,
        goRelation: false,
        authenticateNumber: '',
        relation: false,
        btnText: '提交',
        isNeedAuthSalaryCard: false,
        recruitInfo: {},
        captcha: '',
        showDialog: false,
        errorMsg: '', // 注册是验证是否注册的报错消息
    },
    async onShow() {
        let pages = getCurrentPages() // 获取当前页面信息栈
        let prevPage = pages[pages.length - 2] // 拿到前两级路由信息
        console.log(prevPage.route, 'EPSILON')
        const eventChannel = this.getOpenerEventChannel()
        this.setData({
            isNeedAuthSalaryCard: user.isNeedAuthSalaryCard,
            ['dataInformation.params.prevPage']: prevPage.route
        })
        console.log(this.data.dataInformation, 'this.data.dataInformation')
        eventChannel.on('acceptDataFromOpenerPage', (data) => {
            this.setData({
                'dataInformation.phone': data.phone
            })
        })
        if (this.data.authenticateNumber && app.options.scene == 1038) {
            const queryResult = queryVerifyResult({
                authenticateNumber: this.data.authenticateNumber,
                companyId: app.globalData.companyId
            })
            if (queryResult.authenticateState === 'AUTHENTICATE_SUCCESS') {
                app.globalData.homePath = app.globalData.homePath + encodeURIComponent('&authenticateNumber=' + this.data.authenticateNumber)
                this.setData({
                    relation: true
                })
                this.register()
            }
            app.options = {}
        } else if (this.data.dataInformation.userName && this.data.goRelation) {
            console.log('开通微工卡 进入该判断')
            try {
                await querySalaryCard(app.globalData.companyId)
                this.setData({
                    relation: true
                })
                app.globalData.companyId = ''
                this.register()
            } catch (e) {
                await app.confirm('开通微工卡失败，是否暂时跳过？')
                this.setData({
                    goRelation: false
                })
                app.globalData.companyId = ''
                this.register()
            }
        }
    },
    async onLoad(options) {
        console.log(user.isOpenSalaryCard, 'user.isOpenSalaryCard')
        if (/type=5/.test(decodeURIComponent(app.globalData.homePath))) {
            this.setData({
                btnText: '加入项目'
            })
        }
        // 
        if (/force/.test(decodeURIComponent(global.registerBack.split('scene=')[1]))) {
            const option = {}
            const scene = decodeURIComponent(global.registerBack.split('scene=')[1]).split('&')
            console.log(scene, 'scenescenescenescene')
            for (const i in scene) {
                const query = scene[i].split('=')
                option[query[0]] = query[1]
            }
            this.setData({
                btnText: option.force == '1' ? '开通微工卡' : '提交',
                recruitInfo: option
            })
            console.log(this.data.recruitInfo, 'recruitInfo')
        }
        await user.waitLogin()
        if (user.userId && (user.ownIdCardBack && user.ownIdCardFront) && !options.isEdit) {
            wx.switchTab({
                url: '/pages/index/index',
            })
        }
        if (user.userId) {
            this.setData({
                phone: user.phone,
            })
            getEcho({}).then(res => {
                this.setData({
                    dataInformation: res,
                    isEdit: !!options.isEdit,
                    judgeId: false // 更新
                })
            })
            querySalaryCard(app.globalData.companyId).then(() => {
                this.setData({
                    relation: true
                })
            })
        } else {
            this.setData({
                authStatus: false
            })
        }
    },

    inputChange(event) {
        inputchange(event, this)
    },
    async getPhoneNumber(res) {
        if (!user.session_key) {
            await app.alert('操作过于频繁，请重新打开小程序')
            wx.reLaunch({
                url: '/pages/index/index',
            })
            return
        }
        // 判断是否拿到手机号信息
        if (!res.detail.encryptedData) {
            app.toast('请检查网络是否稳定，后重新获取手机号')
            return
        }
        const data = {
            appId: app.globalData.appId,
            encryptedData: res.detail.encryptedData,
            sessionKey: user.session_key,
            iv: res.detail.iv
        }
        const result = await encryptedPhoneData(data)
        user.phoneNum = res.phoneNumber
        this.setData({
            'dataInformation.phone': result.phoneNumber
        })

    },
    inputPhoneChange(event) {
        this.setData({
            'dataInformation.phone': event.detail.value
        })
    },
    async submit() {
        this.data.dataInformation.userName = this.data.dataInformation.userName.replace(/\./g, '·')
        // 检验姓名中是否存在特殊符号
        const special = /\ |\【|\】|\（|\）|\，|\。|\？|\、|\；|\：|\‘|\’|\“|\”|\！|\《|\》|\￥|\……|\——|\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\|/
        if (special.test(this.data.dataInformation.userName)) {
            app.toast('姓名中不可携带特殊符号')
            return 0
        }
        if (/(\-|\+)?\d+(\.\d+)*/.test(this.data.dataInformation.userName)) {
            app.toast('姓名中不可携带数字')
            return 0
        }
        // 去除 姓名 身份证号 前后空格
        this.setData({
            'dataInformation.idCardNo': this.data.dataInformation.idCardNo.replace(/(^\s*)|(\s*$)/g, ''),
            'dataInformation.userName': this.data.dataInformation.userName.replace(/(^\s*)|(\s*$)/g, '')
        })
        if (!/[^x00-xff]/.test(this.data.dataInformation.userName)) {
            app.toast('请输入您的姓名')
            return 0
        }

        if (!/^\d{17}[\dXx]$/.test(this.data.dataInformation.idCardNo)) {
            app.toast('请输入正确的身份证号码')
            return 0
        }
        // 校验手机号
        if (!/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(this.data.dataInformation.phone)) {
            app.toast('请输入正确格式的手机号码')
            return
        }
        if (!this.data.dataInformation.phone) {
            app.toast('请授权获取手机号码')
            return 0
        }
        
        await this.getUserAccountInfo()

        if (!this.data.captcha) {
            wx.navigateTo({
                url: '/pages/verify-yard/verify-yard?phone=' + this.data.dataInformation.phone,
                success: (res)=> {
                    // 通过eventChannel向被打开页面传送数据
                    res.eventChannel.emit('dataFromBasic', {
                        data: {
                            phone: this.data.dataInformation.phone,
                            isNeedAuthSalaryCard: this.data.isNeedAuthSalaryCard,
                            userName: this.data.dataInformation.userName,
                            idCardNo: this.data.dataInformation.idCardNo,
                            relation: this.data.relation,
                            force: this.data.recruitInfo.force,
                            goRelation: false
                        }
                    })
                }
            })
            return
        }
        // if(this.data.isEdit && !this.data.dataInformation.ownIdCardFront && user.userId){
        //     app.toast('请上传身份证正面')
        //     return 0
        // }
        // if(this.data.isEdit && !this.data.dataInformation.ownIdCardBack && user.userId){
        //     app.toast('请上传身份证反面')
        //     return 0
        // }
        console.log(app.globalData.homePath, '分割', decodeURIComponent(app.globalData.homePath))
        if (this.data.isNeedAuthSalaryCard && user.isOpenSalaryCard == 0 && (/type=0/.test(decodeURIComponent(app.globalData.homePath)) || /type=1/.test(decodeURIComponent(app.globalData.homePath)))) {
            console.log('强制开通微工卡')
            const result = await openSalaryCard(app.globalData.companyId, this.data.dataInformation.userName, this.data.dataInformation.idCardNo)
            this.setData({
                goRelation: result.subMchid
            })
        } else if (this.data.relation) {
            console.log('暂时不知道')
            this.register()
        } else {
            // 微保项目强制认证微工卡
            console.log(/type=4/.test(decodeURIComponent(app.globalData.homePath), /type=4/.test(decodeURIComponent(app.globalData.homePath))))
            if (/type=4/.test(decodeURIComponent(app.globalData.homePath))) {
                console.log('微保项目强制认证微工卡')
                const result = await openSalaryVerify(app.globalData.companyId, app.globalData.companyName, app.globalData.projectId, app.globalData.projectName, this.data.dataInformation.userName, this.data.dataInformation.idCardNo)
                this.setData({
                    goRelation: result.subMchid,
                    authenticateNumber: result.authenticateNumber
                })
            }
            // 国寿财项目强制跳过微工卡
            else if (/type=5/.test(decodeURIComponent(app.globalData.homePath))) {
                console.log('进入国寿财项目')
                this.setData({
                    goRelation: false
                })
                this.register()
            } else if (this.data.recruitInfo.force === '0') {
                // 招聘二维码  标签没强制开通微工卡
                console.log('招聘二维码  标签没强制开通微工卡')
                this.register()
            } else {
                try {
                    const result = await querySalaryCard(app.globalData.companyId)
                    console.log(result, 'result')
                    this.setData({
                        goRelation: result.subMchid
                    })
                    this.register()
                } catch (e) {
                    if (e) {
                        try {
                            await app.confirm('开通微工卡后即可提现到银行卡，是否立即绑定微工卡？', '去绑定', '暂不绑定')
                            const result = openSalaryCard(app.globalData.companyId, this.data.dataInformation.userName, this.data.dataInformation.idCardNo)
                            this.setData({
                                goRelation: result.subMchid
                            })
                        } catch (e) {
                            this.setData({
                                goRelation: false
                            })
                            this.register()
                        }
                    } else {
                        this.setData({
                            goRelation: false
                        })
                        this.register()
                    }

                }


            }
        }
        return 0
    },
    async register() {
        this.data.dataInformation.openId = user.openid
        this.data.dataInformation.userHeadUrl = user.avatarUrl
        this.data.dataInformation.bankCardIs = 1
        this.data.dataInformation.userName = this.data.dataInformation.userName.replace(/\s*/g, '')
        this.data.dataInformation.isOpenSalaryCard = Number(this.data.goRelation)
        console.log(this.data.dataInformation, 'prevPage')
        const result = await register(this.data.dataInformation)
        if (result === 'needPhoto') {
            app.toast('您的身份信息校验失败，请上传您的身份照片后重试')
            this.setData({
                isEdit: true
            })
            return
        }
        await user.init()
        await user.reLogin()
        app.toast('注册成功，正在为您跳转...')
        if (/type=5/.test(decodeURIComponent(app.globalData.homePath)) && app.globalData.gscJoin) {
            app.globalData.gscJoin()
            return
        }
        setTimeout(() => {
            if (app.globalData.homePath) {
                wx.redirectTo({
                    url: '/pages/join/join',
                })
            } else if (app.globalData.registerBack) {
                wx.redirectTo({
                    url: app.globalData.registerBack,
                })
                app.globalData.registerBack = ''
            } else {
                wx.switchTab({
                    url: '/pages/index/index'
                })
            }
        }, 1000)
    },

    // 点击身份证
    async photograph() {
        const image = await wx.chooseMedia({
            count: 1,
            sizeType: ['compressed'],
        })
        console.log(image.tempFiles[0].tempFilePath, 'image')
        const compressImage = await wx.compressImage({
            src: image.tempFiles[0].tempFilePath, // 图片路径
            quality: 50 // 压缩质量
        })
        const base64 = await wxfileTobase64(compressImage.tempFilePath)
        const result = await distinguishIdCard({
            idCard: base64
        })
        if ('name' in result.data.idCardInfo) {
            if (this.data.dataInformation.userName == '' || this.data.dataInformation.idCardNo == '') {
                this.setData({
                    ['dataInformation.userName']: result.data.idCardInfo.name,
                    ['dataInformation.idCardNo']: result.data.idCardInfo.code,
                    ['dataInformation.ownIdCardFront']: result.data.url,
                    judgeId: false
                })
                return 0
            }
            if (result.data.idCardInfo.name == this.data.dataInformation.userName || result.data.idCardInfo.code == this.data.dataInformation.idCardNo) {
                this.setData({
                    ['dataInformation.userName']: result.data.idCardInfo.name,
                    ['dataInformation.idCardNo']: result.data.idCardInfo.code,
                    ['dataInformation.ownIdCardFront']: result.data.url,
                    judgeId: false
                })
            } else {
                app.alert('身份证照片和当前身份信息不符')
            }
        } else {
            this.setData({
                ['dataInformation.ownIdCardBack']: result.data.url
            })
        }
    },
    getUser() {
        this.setData({
            authStatus: true
        })
    },

    onCloseDialog() {
        this.setData({
            showDialog: false
        })
    },
    async getUserAccountInfo() {
        return new Promise(async (resolve, reject) => {
            const res = await checkUserAccount({
                phone: this.data.dataInformation.phone,
                idCardNo: this.data.dataInformation.idCardNo,
                platform: 0,
                openId: user.openid,
                userName: this.data.dataInformation.userName
            }, {
                isToast: false
            }).catch(err => {
                app.alert(err?.data?.msg || '请求错误')
                throw new Error('error')
            })

            if (res?.code === 100) {
                this.setData({
                    showDialog: true,
                    errorMsg: res.msg
                })
                reject(false)
            } else {
                resolve(true)
            }
        })
    },

    async onLogoutLast() {
        const res = await queryLogoutStatus({
            idCardNo: this.data.dataInformation.idCardNo
        })

        if (!res) {
            wx.navigateTo({
                url: '/pages/logout-last/logout-last?idCardNo=' + this.data.dataInformation.idCardNo,
            })
            return
        }

        if (res.status === 0 || res.status === 2) {
            wx.navigateTo({
                url: `/pages/appeal-status/appeal-status?status=${res.status}&idCardNo=${this.data.dataInformation.idCardNo}&rejectRemark=${res.rejectRemark}&originPhone=${res.originPhone}`,
            })
        }
    },
})
